<template>
  <div>
    <div class="ContentBox">
      <div class="InputBoxs">
        <el-form ref="Form" :model="FormData" label-width="20px" class="Forms" :rules="rules">
          <!-- 1 -->
          <el-form-item prop="code">
            <template>
              <div class="text required">{{ ParentData.twoPo }}</div>
              <el-input v-model="FormData.code" :placeholder="core" style="width: 233px;" :disabled="true" />
            </template>
          </el-form-item>
          <!-- 2 -->
          <el-form-item prop="warehouseId">
            <template>
              <div class="text required">{{ '货品类型' }}</div>
              <el-autocomplete
                v-model="state"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                style="width: 233px;"
                suffix-icon="el-icon-search"
                :trigger-on-focus="false"
                @select="handleSelect"
                @input="mounteds('warehouseId')"
              />
            </template>
          </el-form-item>
          <!-- 3 -->
          <el-form-item prop="name">
            <template>
              <div class="text required">{{ ParentData.fourPo }}</div>
              <el-input v-model="FormData.name" placeholder="请输入" style="width: 233px;" />
            </template>
          </el-form-item>
          <!-- 4 -->
          <el-form-item prop="barCode">
            <template>
              <div class="text required">{{ ParentData.threePo }}</div>
              <el-input v-model="FormData.barCode" placeholder="请输入" style="width: 233px;" />
            </template>
          </el-form-item>
          <el-row type="flex" style="width: 100%;">
            <!-- 5 -->
            <el-form-item prop="users">
              <template>
                <div class="text required">{{ '货主' }}</div>
                <el-autocomplete
                v-model="states"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                style="width: 233px;"
                suffix-icon="el-icon-search"
                :trigger-on-focus="false"
                @select="handleSelect"
                @input="mounteds('bearingType')"
              />
              </template>
            </el-form-item>
            <!-- 7 -->
            <el-form-item prop="inspectionType">
              <template>
                <div class="text required">{{ ParentData.sixPo }}</div>
              </template>
              <el-select v-model="FormData.inspectionType" placeholder="请选择" style="width: 233px;" clearable>
                <el-option v-for="(item, index) in this.$store.state.PublicData.HPinspectionType" :key="index" :label="item" :value="index" />
              </el-select>
            </el-form-item>
            <!-- 6 -->
            <el-form-item prop="temperatureType" style="width: 233px;">
              <template>
                <div class="text required">{{ ParentData.sevenPo }}</div>
                <el-select v-model="FormData.temperatureType" placeholder="请选择" style="width: 233px;" clearable>
                  <el-option v-for="(item, index) in this.$store.state.PublicData.HPtemperatureType" :key="index" :label="item" :value="index" />
                </el-select>
              </template>
            </el-form-item>
            <!-- 8 -->
            <el-form-item prop="bearingType" style="width: 233px; margin-left:20px;">
              <template>
                <div class="text required">{{ ParentData.eightPo }}</div>
                <el-select v-model="FormData.bearingType" placeholder="请选择" style="width: 233px;" clearable>
                  <el-option v-for="(item, index) in this.$store.state.PublicData.HPbearingType" :key="index" :label="item" :value="index" />
                </el-select>
              </template>
            </el-form-item>
          </el-row>
          <el-row type="flex" style="width: 100%;">
            <!-- 9 -->
            <el-form-item prop="volume">
              <template>
                <div class="text required">{{ '体积' }}</div>
                <el-input v-model="FormData.volume" placeholder="请输入" style="width: 233px;">
                  <template slot="append">m3</template>
                </el-input>
              </template>
            </el-form-item>
            <!-- 9 -->
            <el-form-item prop="phone">
              <template>
                <div class="text">{{ ParentData.ninePo }}</div>
                <el-select v-model="FormData.useType" placeholder="请选择" style="width: 233px;" clearable>
                  <el-option v-for="(item, index) in reservoirData" :key="index" :label="item.name" :value="item.id" />
                </el-select>
              </template>
            </el-form-item>
            <el-form-item prop="price">
              <template>
                <div class="text">{{ ParentData.tenOnPo }}</div>
                <el-input v-model="FormData.price" placeholder="请输入" style="width: 233px;">
                  <template slot="append">元</template>
                </el-input>
              </template>
            </el-form-item>
            <el-form-item prop="unit">
              <template>
                <div class="text">{{ ParentData.tenTwoPo }}</div>
                <el-input v-model="FormData.unit" placeholder="请输入" style="width: 233px;" />
              </template>
            </el-form-item>
          </el-row>
          <el-form-item prop="guaranteeDay">
            <template>
              <div class="text">{{ ParentData.tenThreePo }}</div>
              <el-input v-model="FormData.guaranteeDay" placeholder="请输入" style="width: 233px;">
                <template slot="append">天</template>
              </el-input>
            </template>
          </el-form-item>
          <!-- 按钮 -->
        </el-form>
        <div class="FormInBtn">
          <el-divider />
          <div class="FormBtn">
            <el-button type="warning" style="background-color: #f8f5f5;" @click.native="Back">返回</el-button>
            <el-button type="warning" @click="Submit">提交</el-button>
          </div>
          <el-divider />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  NewCode, GetAllWarehouseList, AllReservoir,
  FuzzyQueryGoods, FuzzyQueryShipper, AddGoods, QueryGoods, ModifyGoods
} from '@/api'
import RouteData from '@/utils/RouteData'
export default {
  data() {
    return {
      // 编码
      core: '',
      ParentData: {},
      FormData: {},
      list: {},
      rules: {
        name: [
          { required: true, message: '请输入所属仓库', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入库区名称', trigger: 'blur' }
        ],
        selectedOptions: [
          { required: true, message: '请输入温度类型', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入承重类型', trigger: 'blur' }
        ],
        surface: [
          { required: true, message: '请输入用途属性', trigger: 'blur' }
        ]
      },
      params: '',
      FuzzyQueryGoodsData: [],
      FuzzyQueryShipperData: [],
      restaurants: [],
      state: '',
      states: '',
      timeout: null,
      newArr: [],
      reservoirData: []
    }
  },
  watch: {
    list: {
      immediate: true,
      deep: true,
      async handler() {
        const res = await GetAllWarehouseList({ status: 1 })
        res.data.data.forEach((item) => {
          this.list[item.name] = item.id
        })
      }
    }
  },
  created() {
    this.$route.meta.title = '编辑库区'
    // 全量数据
    this.GetAllWarehouse()
    // 拿去路由数据渲染字段
    this.ParentData = RouteData(this.$route)
    // 编码
    this.NewCodeFn()
    if (this.$route.query.Id) {
      this.QueryWarehouseAreaFn()
    }
    this.FuzzyQueryGoodsFn()
    this.FuzzyQueryShipperFn()
  },
  methods: {
    // 搜索框模糊查询
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
        this.status = results
      }, 3000 * Math.random())
    },
    createStateFilter(queryString) {
      return (state) => {
        this.newArr = []
        this.newArr = (state.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
        return this.newArr
      }
    },
    async mounteds(item) {
      if (item === 'warehouseId') {
        this.restaurants = this.FuzzyQueryGoodsData.map((item) => { return { value: item.name, address: item.id } })
        return
      }
      if (item === 'bearingType') {
        this.restaurants = this.FuzzyQueryShipperData.map((item) => { return { value: item.name, address: item.id, pipo: 1 } })
        return
      }
    },
    // 模糊搜索选择
    async handleSelect(item) {
      if (item.pipo) {
        const res = await AllReservoir({ ownerId: item.address })
        this.reservoirData = res.data.data
        this.FormData.ownerName = item.value
        this.FormData.ownerId = item.address
        return
      }
      this.FormData.goodsTypeName = item.value
      this.FormData.goodsTypeId = item.address
      console.log(this.FormData)
    },
    async FuzzyQueryGoodsFn() {
      const res = await FuzzyQueryGoods({ params: '' })
      this.FuzzyQueryGoodsData = res.data.data
    },
    async FuzzyQueryShipperFn() {
      const res = await FuzzyQueryShipper({ params: '' })
      this.FuzzyQueryShipperData = res.data.data
    },
    // 提交
    async Submit() {
      this.$refs.Form.validate(async(vala) => {
        if (vala) {
          try {
            let msg = ''
            // Id为真时，编辑模式
            if (this.$route.query.Id) {
              console.log(1)
              msg = await ModifyGoods(this.FormData)
            } else {
              // 添加模式
              console.log(2)
              msg = await AddGoods(this.FormData)
            }
            if (msg.data.isSuccess) {
              this.$router.go(-1)
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$message({
                message: msg.data.msg,
                type: 'success'
              })
              return
            }
            if (msg.data.isError) {
              this.$message({
                message: msg.data.msg,
                type: 'warning'
              })
              return
            }
          } catch (err) {
            console.log(err)
          }
        }
      })
    },
    // 获取新编号
    async NewCodeFn() {
      const res = await NewCode('HP')
      this.core = res.data.data
      this.FormData.code = this.core
    },
    // 拿取全量数据
    async GetAllWarehouse() {
      const res = await GetAllWarehouseList({ status: 1 })
      res.data.data.forEach((item) => {
        this.list[item.name] = item.id
      })
    },
    // 数据回显
    async QueryWarehouseAreaFn() {
      const res = await QueryGoods(this.$route.query.Id)
      this.FormData = res.data.data
    },
    // 返回
    Back() {
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    }
  }
}
</script>
<style>
</style>
